package com.tju.resource.business.tb_retreat.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tju.resource.business.tb_retreat.TbRetreatService;
import com.tju.resource.common.ServiceException;
import com.tju.resource.mapper.*;
import com.tju.resource.model.*;
import com.tju.resource.result.Result;
import com.tju.resource.result.ResultEnum;
import com.tju.resource.result.ResultUtil;
import com.tju.resource.tool.tool.EmptyUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.Map;

import static com.tju.resource.tool.tool.WeightParser.parse;
import static com.tju.resource.tool.tool.WeightParser.toUnit;

/**
 * 退料管理
 */
@Service
public class TbRetreatServiceImpl extends ServiceImpl<TbRetreatMapper, TbRetreat>
        implements TbRetreatService {
    @Autowired
    private TbRetreatMapper tbRetreatMapper;
    @Autowired
    private TbProdPlanMapper tbProdPlanMapper;
    @Autowired
    private TbMaterialMapper tbMaterialMapper;
    @Autowired
    private TbConsumablesMapper tbConsumablesMapper;
    @Autowired
    private TbRawMatlMapper tbRawMatlMapper;

    /**
     * 查询退料记录
     *
     * @param pa 查询参数
     * @return
     */
    @Override
    public Result<Object> selectRetreat(Map<String, String> pa) {
        String page = pa.get("page"); //页数
        String limit = pa.get("limit"); //页码
        if(EmptyUtils.isNotEmpty(page)&&EmptyUtils.isNotEmpty(limit)){
            Page<TbRetreat> retreatPage =new Page<>(Integer.parseInt(page),Integer.parseInt(limit)); //分页模型
            IPage<TbRetreat> iPage=tbRetreatMapper.selectRetreat(retreatPage,pa);
            return ResultUtil.success(ResultEnum.SUCCESS, iPage.getRecords(),iPage.getTotal());
        }
        return ResultUtil.error(ResultEnum.UNKONW_ERROR,"缺少参数");
    }

    /**
     * 添加退料记录
     *
     * @param tbRetreat 参数
     * @return
     */
    @Transactional
    @Override
    public Result<Object> addRetreat(TbRetreat tbRetreat) {
        if (tbRetreatMapper.insert(tbRetreat) > 0) {
            return ResultUtil.success(ResultEnum.SUCCESS, "添加成功");
        }
        return ResultUtil.error(ResultEnum.UNKONW_ERROR, "添加失败");
    }

    /**
     * 修改退料记录
     *
     * @param tbRetreat 参数
     * @return
     */
    @Transactional
    @Override
    public Result<Object> editRetreat(TbRetreat tbRetreat) {
        if (EmptyUtils.isNotEmpty(tbRetreat.getId())) {
            if (tbRetreatMapper.updateById(tbRetreat) > 0) {
                return ResultUtil.success(ResultEnum.SUCCESS, "修改成功");
            }
            return ResultUtil.error(ResultEnum.UNKONW_ERROR, "修改失败");
        }
        return ResultUtil.error(ResultEnum.UNKONW_ERROR, "缺少参数");
    }

    /**
     * 删除退料记录
     *
     * @param tbRetreat 参数
     * @return
     */
    @Transactional
    @Override
    public Result<Object> deleteRetreat(TbRetreat tbRetreat) {
        if (EmptyUtils.isNotEmpty(tbRetreat.getId())) {
            TbRetreat retreat = tbRetreatMapper.selectById(tbRetreat.getId());
            if(EmptyUtils.isEmpty(retreat))
                return ResultUtil.error(ResultEnum.UNKONW_ERROR,"不存在退料id: "+tbRetreat.getId());
            else if(retreat.getAppState()==2 ||retreat.getAppState()==1)
                return ResultUtil.error(ResultEnum.UNKONW_ERROR, "不能取消重复退料id: " + tbRetreat.getId());
            tbRetreat.setAppState(2);//取消
            tbRetreat.setAppTime(new Date());//取消时间
            if (tbRetreatMapper.updateById(tbRetreat) > 0) {
                return ResultUtil.success(ResultEnum.SUCCESS, "取消退料成功");
            }
            return ResultUtil.error(ResultEnum.UNKONW_ERROR, "取消退料失败");
        }
        return ResultUtil.error(ResultEnum.UNKONW_ERROR, "缺少参数");
    }

    /**
     * 审核退料记录
     *
     * @param tbRetreat 参数
     * @return 结果
     */
    @Transactional
    @Override
    public Result<Object> approveRetreat(TbRetreat tbRetreat) {
        Long id = tbRetreat.getId(); //退料id
        if (EmptyUtils.isNotEmpty(id)) {
            TbRetreat retreat = tbRetreatMapper.selectById(id);
            if(EmptyUtils.isEmpty(retreat))
                return ResultUtil.error(ResultEnum.UNKONW_ERROR,"不存在退料id: "+id);
            else if(retreat.getAppState()==1 ||retreat.getAppState()==2)
                return ResultUtil.error(ResultEnum.UNKONW_ERROR, "不能重复审核退料id: " + id);
            retreat.setAppBy(tbRetreat.getAppBy());//审核人
            retreat.setAppState(1);//已审核
            retreat.setAppTime(new Date());//审核时间
            int type = retreat.getType();  //退料类型
            Integer qty = retreat.getQty(); //退料数

            if(type ==1){
                //查询耗材
                TbConsumables tbConsumables = tbConsumablesMapper.selectById(retreat.getConsumablesId());
                if (EmptyUtils.isEmpty(tbConsumables))
                    return ResultUtil.error(ResultEnum.UNKONW_ERROR,"不存在耗材id: "+retreat.getConsumablesId());
                tbConsumables.setNumber(tbConsumables.getNumber()+qty);  //耗材原来库存加上退料库存
                if (tbConsumablesMapper.updateById(tbConsumables)==0)
                    throw new ServiceException("修改耗材库存失败");
            }else if(type ==0){
                //查询原料
                TbRawMatl rawMatl = tbRawMatlMapper.selectById(retreat.getRmId());
                if (EmptyUtils.isEmpty(rawMatl))
                    return ResultUtil.error(ResultEnum.UNKONW_ERROR,"不存在原料id: "+retreat.getRmId());
                if(rawMatl.getRmType()==1){
                    double weight = retreat.getWeight(); //退料重量
                    if(EmptyUtils.isEmpty(weight))
                        return ResultUtil.error(ResultEnum.UNKONW_ERROR,"原料退料的重量不能为空");
                    rawMatl.setRmStoke(rawMatl.getRmStoke()+weight);  //原料库存加上退料重量
                }else{
                    rawMatl.setRmStoke(rawMatl.getRmStoke()+qty);  //原料库存加上退料数量
                }
                if (tbRawMatlMapper.updateById(rawMatl)==0)
                    throw new ServiceException("修改原料库存失败");
            }else {
                return ResultUtil.error(ResultEnum.UNKONW_ERROR,"审核失败");
            }
            if (tbRetreatMapper.updateById(retreat)==0) //修改退料
                throw new ServiceException("退料失败");
            return ResultUtil.success(ResultEnum.SUCCESS,"退料成功");
        }
        return ResultUtil.error(ResultEnum.UNKONW_ERROR,"缺少参数");
    }

    @Override
    @Transactional
    public Result<Object> addRetreatList(TbRetreat retreat) {
        //判断生产计划不为空的时候查询生产计划是否存在
        Long ppId = retreat.getPpId(); //生产计划id
        if (EmptyUtils.isNotEmpty(ppId))
            if (EmptyUtils.isEmpty(tbProdPlanMapper.selectById(ppId)))
                return ResultUtil.error(ResultEnum.UNKONW_ERROR, "不存在生产计划id: "+ ppId);
        //判断其中一个不为空就进入
        if(EmptyUtils.isNotEmpty(retreat.getConsumablesList())) {
            //循环耗材
            for (TbConsumables consumables : retreat.getConsumablesList()) {
                Long consumablesId = consumables.getId(); //耗材id
                if (EmptyUtils.isEmpty( tbConsumablesMapper.selectById(consumablesId)))
                       throw new ServiceException(String.format("不存在耗材id: %s", consumablesId));
                retreat.setType(1); //耗材类型
                retreat.setConsumablesId(consumablesId);  //耗材id
                if (EmptyUtils.isEmpty(consumables.getQty()))
                    throw new ServiceException("请输入退料数量");
                retreat.setQty(consumables.getQty()); //耗材数量
                retreat.setRemark(consumables.getRemark());//耗材备注
                //添加退料记录
                if (tbRetreatMapper.insert(retreat) == 0)
                    throw new ServiceException("退料失败!");
            }
        }else if(EmptyUtils.isNotEmpty(retreat.getRawMatlList())){
            //循环原料
            for (TbRawMatl rawMatl : retreat.getRawMatlList()) {
                Long rmId = rawMatl.getId(); //耗材id
                TbRawMatl tbRawMatl = tbRawMatlMapper.selectById(rmId); //原料
                if (EmptyUtils.isEmpty(tbRawMatl))
                    throw new ServiceException(String.format("不存在原料id: %s", rmId));
                retreat.setRmId(rmId);  //耗材id
                if(tbRawMatl.getRmType()==2){
                    if (EmptyUtils.isEmpty(rawMatl.getRmRadio()))
                        throw new ServiceException(tbRawMatl.getRmName()+" 请输入退料数量");
                    retreat.setQty(rawMatl.getRmRadio()); //原料数量
                    retreat.setWeight(null);
                }else {
                    Double rmFmWg = rawMatl.getRmFmWg();  //退料单位
                    if (EmptyUtils.isEmpty(rmFmWg))
                        throw new ServiceException(tbRawMatl.getRmName()+" 请输入退料重量");
                    else if(EmptyUtils.isEmpty(rawMatl.getRmUnit())){
                        throw new ServiceException(tbRawMatl.getRmName()+" 请选择重量单位");
                    }
                    Double deficiencyWeight = parse(rmFmWg, toUnit(rawMatl.getRmUnit()), toUnit(tbRawMatl.getRmUnit()));
                    retreat.setWeight(deficiencyWeight); //原料重量
                    retreat.setQty(null);
                }
                retreat.setType(0); //原料类型
                retreat.setRemark(rawMatl.getRemark());//原料备注
                //添加退料记录
                if (tbRetreatMapper.insert(retreat) == 0)
                    throw new ServiceException("退料失败!");
            }
        }else {
            return ResultUtil.error(ResultEnum.UNKONW_ERROR, "缺少参数");
        }
        return ResultUtil.success(ResultEnum.SUCCESS, "退料成功");

    }

    /**
     * 根据生产计划id查询原料
     *
     * @param tbRetreat 参数
     * @return 结果
     */
    @Override
    public Result<Object> selectRm(Map<String, String> tbRetreat) {
        if (EmptyUtils.isNotEmpty(tbRetreat.get("ppId")) && EmptyUtils.isNotEmpty(tbRetreat.get("page")) && EmptyUtils.isNotEmpty(tbRetreat.get("limit"))) {
            //查询生产计划
            TbProdPlan ppId = tbProdPlanMapper.selectById(tbRetreat.get("ppId"));
            //不存在为空 物料id为空也是不存在
            if (EmptyUtils.isEmpty(ppId)||EmptyUtils.isEmpty(ppId.getMatlId()))
                ResultUtil.error(ResultEnum.UNKONW_ERROR, "生产计划不存在");
            tbRetreat.put("matlId", ppId.getMatlId() + "");  //查询条件
            Page<TbRmMatl> page = new Page<>(Integer.parseInt(tbRetreat.get("page")), Integer.parseInt(tbRetreat.get("limit")));
            IPage<TbRmMatl> tbRmMatlIPage = tbMaterialMapper.selectTbRmMatlList(page, tbRetreat);
            return ResultUtil.success(ResultEnum.SUCCESS, tbRmMatlIPage.getRecords(), tbRmMatlIPage.getTotal());
        }
        return ResultUtil.error(ResultEnum.UNKONW_ERROR, "缺少参数");
    }

    /**
     * 根据生产计划id查询耗材
     *
     * @param tbRetreat 参数
     * @return 结果
     */
    @Override
    public Result<Object> selectConsumables(Map<String, String> tbRetreat) {
        if (EmptyUtils.isNotEmpty(tbRetreat.get("ppId")) && EmptyUtils.isNotEmpty(tbRetreat.get("page")) && EmptyUtils.isNotEmpty(tbRetreat.get("limit"))) {
            //查询生产计划
            TbProdPlan ppId = tbProdPlanMapper.selectById(tbRetreat.get("ppId"));
            //不存在为空
            if (EmptyUtils.isEmpty(ppId)||EmptyUtils.isEmpty(ppId.getMatlId()))
                ResultUtil.error(ResultEnum.UNKONW_ERROR, "生产计划不存在");
            tbRetreat.put("matlId", ppId.getMatlId() + "");  //查询条件
            Page<TbMatlConsumables> page = new Page<>(Integer.parseInt(tbRetreat.get("page")), Integer.parseInt(tbRetreat.get("limit")));
            IPage<TbMatlConsumables> tbMatlConsumablesIPage = tbMaterialMapper.selectMatlConsumablesList(page, tbRetreat);
            return ResultUtil.success(ResultEnum.SUCCESS, tbMatlConsumablesIPage.getRecords(), tbMatlConsumablesIPage.getTotal());
        }
        return ResultUtil.error(ResultEnum.UNKONW_ERROR, "缺少参数");
    }

}




